package com.caifu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Util;
import com.caifu.vo.BmUserinfoVo;
import com.caifu.vo.DataUserAgeVo;
import com.caifu.vo.DataVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author tianwenwen
 * ClassName: BmUserinfoService.java
 * version: 1.0.0
 * createTime: 2020年10月16日 10:59:58
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class BmmUserinfoService {

    @Resource
    private BmmUserinfoMapper bmmUserinfoMapper;

    @Resource
    private CouponsRecordMapper couponsRecordMapper;

    @Resource
    private YsLabelMapper ysLabelMapper;

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private BmActivityManagerMapper bmActivityManagerMapper;


    /**
     * description: 添加老人优惠信息
     * param type ids
     * return: void
     * author: Tian
     * time: 2020/10/16 15:52
     */
    public Result addBmUserinfo(String type, String ids, String coupons, SysUser user) {
        if (Util.isNotNull(ids)) {
            String[] arrId = ids.split(",");
            for (String id : arrId) {
                //添加之前判断老人优惠信息是否存在
                if (bmUserinfoIsExist(id, type)) {
                    continue;
                }
                BmUserinfo bmUserinfo = new BmUserinfo();
                bmUserinfo.setTotalCoupons(Integer.parseInt(coupons));
                bmUserinfo.setUnusedCoupons(Integer.parseInt(coupons));
                bmUserinfo.setUsedCoupons(0);
                bmUserinfo.setType(type);
                bmUserinfo.setCreatedTime(new Date());
                bmUserinfo.setUpdatedTime(new Date());
                bmUserinfo.setUserinfoId(id);
                bmUserinfo.setStatus("1");
                bmmUserinfoMapper.insert(bmUserinfo);

                //添加优惠券记录
                BmCouponsRecord bmCouponsRecord = new BmCouponsRecord();
                bmCouponsRecord.setNumber(coupons);
                bmCouponsRecord.setSourceUse(user.getLoginName());
                bmCouponsRecord.setBmUserinfoId(bmUserinfo.getId());
                bmCouponsRecord.setCreatedTime(new Date());
                bmCouponsRecord.setUpdatedTime(new Date());
                bmCouponsRecord.setType(type);
                bmCouponsRecord.setHairCut("1");
                couponsRecordMapper.insert(bmCouponsRecord);

            }
        }
        return ResultUtil.success(200, "添加成功");
    }

    /**
     * 统计老人是否已经有优惠信息
     */
    public boolean bmUserinfoIsExist(String id, String type) {
        QueryWrapper<BmUserinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userinfo_id", id).eq("type", type).eq("status", "1");
        int count = bmmUserinfoMapper.selectCount(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * description: 获取老人优惠信息列表
     * param param currentPage pageSize
     * return: void
     * author: Tian
     * time: 2020/10/16 16:59
     */
    public PageInfo<BmUserinfoVo> getBmUserinfoList(BmUserinfoVo bmUserinfoVo, SysUser user) throws Exception {
        //获取当前管理员组织架构
        HashSet<Long> sysUserOrgId = getSysUserOrgId(user);
        //获取选中当前节点所有子节点
        List<Long> allOrgIds = getAllOrgIds(bmUserinfoVo.getOrgId());
        PageHelper.startPage(bmUserinfoVo.getCurrentPage(), bmUserinfoVo.getPageSize());
        Map<String, Object> params = new HashMap<>(15);
        params.put("param", bmUserinfoVo.getParam());
        params.put("orgIds", allOrgIds);
        params.put("type", bmUserinfoVo.getType());
        params.put("userOrgIds", sysUserOrgId);
        if (Util.isNotNull(bmUserinfoVo.getUserPid())){
            params.put("userPid", AesMyUtil.Encrypt(bmUserinfoVo.getUserPid()));
        }
        List<BmUserinfoVo> bmUserinfoList = bmmUserinfoMapper.getBmUserinfoList(params);
        //1男
        String sex = "1";
        String fale = "2";
        if (Util.isNotNull(bmUserinfoList) && bmUserinfoList.size() > 0) {
            for (BmUserinfoVo userinfoVo : bmUserinfoList) {
                if (sex.equals(userinfoVo.getUserSex())) {
                    userinfoVo.setUserSex("男");
                } else if (fale.equals(userinfoVo.getUserSex())) {
                    userinfoVo.setUserSex("女");
                } else {
                    userinfoVo.setUserSex("未知");
                }
            }
        }
        return new PageInfo<>(bmUserinfoList);
    }

    /**
     * description: 批量发券
     * param type ids coupons
     * return: void
     * author: Tian
     * time: 2020/10/16 17:44
     */
    public void batchCoupons(String type, String ids, String coupons, SysUser user) {
        if (Util.isNotNull(ids)) {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                UpdateWrapper<BmUserinfo> updateWrapper = new UpdateWrapper<>();
                QueryWrapper<BmUserinfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userinfo_id", id).eq("type", type).eq("status", 1);
                BmUserinfo bmUserinfo = bmmUserinfoMapper.selectOne(queryWrapper);
                if (Util.isNotNull(bmUserinfo)) {
                    int total = bmUserinfo.getTotalCoupons() + Integer.parseInt(coupons);
                    bmUserinfo.setTotalCoupons(total);
                    int unUseds = bmUserinfo.getUnusedCoupons() + Integer.parseInt(coupons);
                    bmUserinfo.setUnusedCoupons(unUseds);

                    updateWrapper.eq("userinfo_id", id).eq("type", type).eq("status", 1);
                    bmmUserinfoMapper.update(bmUserinfo, updateWrapper);
                }


                //添加发券记录
                BmCouponsRecord bmCouponsRecord = new BmCouponsRecord();
                bmCouponsRecord.setSourceUse(user.getLoginName());
                bmCouponsRecord.setNumber(coupons);
                bmCouponsRecord.setUpdatedTime(new Date());
                bmCouponsRecord.setCreatedTime(new Date());
                bmCouponsRecord.setBmUserinfoId(bmUserinfo.getId());
                bmCouponsRecord.setHairCut("1");
                bmCouponsRecord.setType(type);
                couponsRecordMapper.insert(bmCouponsRecord);
            }
        }
    }

    /**
     * description: 批量移除
     * param type ids
     * return: void
     * author: Tian
     * time: 2020/10/16 17:44
     */
    public void batchRemove(String type, String ids) {
        if (Util.isNotNull(ids)) {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                QueryWrapper<BmUserinfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userinfo_id", id).eq("type", type).eq("status", 1);
                BmUserinfo bmUserinfo = bmmUserinfoMapper.selectOne(queryWrapper);
                if (Util.isNotNull(bmUserinfo)) {
                    bmUserinfo.setStatus("9");
                    bmmUserinfoMapper.updateById(bmUserinfo);
                }
            }
        }
    }

    /**
     * description: 根据老人id获取老人详细信息
     * param id
     * param type
     * return: com.caifu.pojo.BmUserinfo
     * author: Tian
     * time: 2020/10/27 17:45
     */
    public BmUserinfoVo getBmUserInfoByid(String id, String type) throws Exception {
        Map<String, Object> map = new HashMap<>(10);
        map.put("id", id);
        map.put("type", type);
        BmUserinfoVo bmUserinfoVo = bmmUserinfoMapper.selectUserinfoByIdMap(map);
        bmUserinfoVo.setUserPid(AesMyUtil.Decrypt(bmUserinfoVo.getUserPid()));
        bmUserinfoVo.setMobile(AesMyUtil.Decrypt(bmUserinfoVo.getMobile()));
        //居住行政区
        bmUserinfoVo.setLiveAreaOfResidence(getOrgName(bmUserinfoVo.getLiveAreaOfResidence()));
        //户籍行政区
        bmUserinfoVo.setRegisterAreaOfResidence(getOrgName(bmUserinfoVo.getRegisterAreaOfResidence()));
        //证件类型
        if (YsLabelIsNull(bmUserinfoVo.getCertificateType())) {
            bmUserinfoVo.setCertificateType(getYsLabelByLabelCode(bmUserinfoVo.getCertificateType()).getLabelName());
        }
        //民族
        if (YsLabelIsNull(bmUserinfoVo.getNation())) {
            bmUserinfoVo.setNation(getYsLabelByLabelCode(bmUserinfoVo.getNation()).getLabelName());
        }
        //政治面貌
        if (YsLabelIsNull(bmUserinfoVo.getPolitical())) {
            bmUserinfoVo.setPolitical(getYsLabelByLabelCode(bmUserinfoVo.getPolitical()).getLabelName());
        }
        //婚姻状况
        if (YsLabelIsNull(bmUserinfoVo.getMarriage())) {
            bmUserinfoVo.setMarriage(getYsLabelByLabelCode(bmUserinfoVo.getMarriage()).getLabelName());
        }
        //社保类型
        if (YsLabelIsNull(bmUserinfoVo.getSocialSecurityType())) {
            bmUserinfoVo.setSocialSecurityType(getYsLabelByLabelCode(bmUserinfoVo.getSocialSecurityType()).getLabelName());
        }
        //所在地区
        if (YsLabelIsNull(bmUserinfoVo.getLocation())) {
            bmUserinfoVo.setLocation(getYsLabelByLabelCode(bmUserinfoVo.getLocation()).getLabelName());
        }
        //文化程度
        if (YsLabelIsNull(bmUserinfoVo.getDegreeOfEducation())) {
            bmUserinfoVo.setDegreeOfEducation(getYsLabelByLabelCode(bmUserinfoVo.getDegreeOfEducation()).getLabelName());
        }

        //出生时间
        if (Util.isNotNull(bmUserinfoVo.getBirthDate())) {
            bmUserinfoVo.setBirthDate(transformDateForLoad(bmUserinfoVo.getBirthDate()));
        }

        //退休时间
        if (Util.isNotNull(bmUserinfoVo.getRetireTime())) {
            bmUserinfoVo.setRetireTime(transformDateForLoad(bmUserinfoVo.getRetireTime()));
        }

        String male = "1";
        String female = "2";
        if (male.equals(bmUserinfoVo.getUserSex())) {
            bmUserinfoVo.setUserSex("男");
        } else if (female.equals(bmUserinfoVo.getUserSex())) {
            bmUserinfoVo.setUserSex("女");
        } else {
            bmUserinfoVo.setUserSex("未知");
        }
        return bmUserinfoVo;
    }

    /**
     * 获取老人优惠券 基本信息
     *
     * @param userInfoId userInfoId
     * @param type       优惠券类型（1.理发2.缝纫）
     * @return BmUserinfo
     */
    public BmUserinfo getBmUserInfoByUserInfoId(String userInfoId, Integer type) {
        QueryWrapper<BmUserinfo> bmUserInfoQueryWrapper = new QueryWrapper<>();
        bmUserInfoQueryWrapper.eq("userinfo_id", userInfoId);
        bmUserInfoQueryWrapper.eq("type", type);
        bmUserInfoQueryWrapper.eq("status", "1");
        return bmmUserinfoMapper.selectOne(bmUserInfoQueryWrapper);
    }

    private boolean YsLabelIsNull(String labelCode) {
        if (Util.isNotNull(getYsLabelByLabelCode(labelCode))) {
            return true;
        }
        return false;
    }

    /**
     * description: 根据id获取yslabel
     * param labelCode
     * return: com.caifu.pojo.YsLabel
     * author: Tian
     * time: 2020/11/2 14:59
     */

    private YsLabel getYsLabelByLabelCode(String labelCode) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_code", labelCode);
        queryWrapper.eq("status", "1");
        return ysLabelMapper.selectOne(queryWrapper);
    }

    /**
     * 给页面展示的时候用
     */
    private String transformDateForLoad(String date) {
        return date.substring(0, 4) + "年" + date.substring(4, 6) + "月" + date.substring(6, 8) + "日";
    }


    /**
     * 获取当前管理员组织架构
     */
    private HashSet<Long> getSysUserOrgId(SysUser user) throws Exception {
        //查询当前管理员类型为3得节点
        Map<String, Object> param = new HashMap<>();
        param.put("userNo", String.valueOf(user.getUserNo()));
        param.put("type", 3);
        List<Map<String, Object>> orgList = sysOrganizationMapper.selectOrgIdsByUserNoAndType(param);
        HashSet<Long> longs = new HashSet<>();
        for (Map<String, Object> map : orgList) {
            String[] codes = map.get("orgPathCode").toString().split(",");
            for (String code : codes) {
                longs.add(Long.parseLong(code));
            }
        }
        return longs;
    }

    /**
     * 获取当前节点所有子节点
     */
    private List<Long> getAllOrgIds(String orgId) {
        ArrayList<Long> orgIds = new ArrayList<>();
        List<Map<String, Object>> list = sysOrganizationMapper.getAllOrganization(orgId);
        for (Map<String, Object> map : list) {
            orgIds.add(Long.parseLong(map.get("orgId").toString()));
        }
        return orgIds;
    }

    /**
     * 根据id获取组织架构name
     */
    public String getOrgName(String orgId) {
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(orgId);
        if (Util.isNotNull(sysOrganization)) {
            return sysOrganization.getOrgName();
        }
        return "";
    }


    /**
     * ================
     * ====数据看板=====
     * ===============
     */

    /**
     * 获取活动室总数
     *
     * @return
     */
    public Integer getActivityNum(HashSet<Long> orgIds) {
        //return bmActivityManagerMapper.selectCount(new QueryWrapper<BmActivityManager>().eq("status", 1).in("org_id", orgIds));
        return bmActivityManagerMapper.selectCount(new QueryWrapper<BmActivityManager>().eq("status", 1));
    }


    /**
     * 获取根据类型获取理发、缝纫老人数
     *
     * @param type
     * @return
     */
    public Integer getBmUserInfoNum(String type, HashSet<Long> orgIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        //map.put("orgIds", orgIds);
        return bmmUserinfoMapper.getBmUserInfoNum(map);
    }

    /**
     * 获取发放总数
     *
     * @param type
     * @param hairCut
     * @return
     */
    public Integer getGrantNum(String type, String hairCut, HashSet<Long> orgIds) {
        //return couponsRecordMapper.getGrantNum(type, hairCut, orgIds);
        return couponsRecordMapper.getGrantNum(type, hairCut, null);
    }

    /**
     * 获取核销总数
     *
     * @param type
     * @param hairCut
     * @return
     */
    public Integer getWriteoffNum(String type, String hairCut, HashSet<Long> orgIds) {
        return couponsRecordMapper.getWriteoffNum(type, hairCut, null);
    }

    /**
     * 获取本月、本年理发店核销
     *
     * @return
     */
    public List<Map<String, Object>> getCurrentMonth(String flag) {
        return couponsRecordMapper.getCurrentMonth(flag);
    }

    /**
     * 根据flag获取理发、缝纫信息总数  1.理发 2.缝纫
     *
     * @param flag
     * @return
     */
    public Map<String, Object> getLiFaOrFengRenByFlag(String flag, SysUser user) throws Exception {
        //获取当前管理员组织架构
        HashSet<Long> orgIds = getSysUserOrgId(user);
        Map<String, Object> map = new HashMap<>(10);
        //是否存在活动室
        Integer activityNum = getActivityNum(orgIds);
        if (activityNum <= 0) {
            map.put("userNum", 0);
            map.put("pinNum", 0);
            map.put("hairNum", 0);
            return map;
        }
        Integer userInfoNum = getBmUserInfoNum(flag, orgIds);
        //消费
        Integer writeoffNum = getWriteoffNum(flag, "2", orgIds);
        //发放
        Integer grantNum = getGrantNum(flag, "1", orgIds);
        map.put("userNum", userInfoNum);
        map.put("pinNum", writeoffNum);
        map.put("hairNum", grantNum);
        return map;
    }

    /**
     * 获取优惠券年龄段
     *
     * @return
     */
    public List<Map<String, Object>> getUserinfoAge(DataUserAgeVo dataUserAgeVo, SysUser user) throws Exception {
        //当前管理员组织架构
        HashSet<Long> orgIds = getSysUserOrgId(user);
        //判断活动室是否存在
        Integer activityNum = getActivityNum(orgIds);

        List<Map<String, Object>> maps = new ArrayList<>();
        if (Util.isNull(activityNum) || activityNum == 0) {
            return maps;
        }
        //查询参数
        Map<String, Object> params = new HashMap<>();
        //根据选中节点获取子几点
        List<Long> allOrgIds = new ArrayList<>();
        if (Util.isNotNull(dataUserAgeVo.getOrgId())) {
            allOrgIds = getAllOrgIds(dataUserAgeVo.getOrgId());
        }
        //65-70岁
        params.put("startAge", 65);
        params.put("endAge", 70);
        //params.put("orgIds", orgIds);
        //params.put("allOrgIds", allOrgIds);

        Integer userinfoAge = bmmUserinfoMapper.getUserinfoAge(params);
        Map<String, Object> map = new HashMap<>(10);
        map.put("name", "65-70岁");
        map.put("value", userinfoAge);
        //71-75岁
        params.put("startAge", 71);
        params.put("endAge", 75);
        Integer userinfoAge2 = bmmUserinfoMapper.getUserinfoAge(params);
        Map<String, Object> map2 = new HashMap<>(10);
        map2.put("name", "71-75岁");
        map2.put("value", userinfoAge2);
        //76-80岁
        params.put("startAge", 76);
        params.put("endAge", 80);
        Integer userinfoAge3 = bmmUserinfoMapper.getUserinfoAge(params);
        Map<String, Object> map3 = new HashMap<>(10);
        map3.put("name", "76-80岁");
        map3.put("value", userinfoAge3);

        //81-85岁
        params.put("startAge", 81);
        params.put("endAge", 85);
        Integer userinfoAge4 = bmmUserinfoMapper.getUserinfoAge(params);
        Map<String, Object> map4 = new HashMap<>(10);
        map4.put("name", "81-85岁");
        map4.put("value", userinfoAge4);

        //86-90岁
        params.put("startAge", 86);
        params.put("endAge", 90);
        Integer userinfoAge5 = bmmUserinfoMapper.getUserinfoAge(params);
        Map<String, Object> map5 = new HashMap<>(10);
        map5.put("name", "86-90岁");
        map5.put("value", userinfoAge5);

        //90以上
        params.put("age", 90);
        Integer userinfoAgeCount = bmmUserinfoMapper.getUserinfoAgeCount(params);
        Map<String, Object> map6 = new HashMap<>(10);
        map6.put("name", "90岁以上");
        map6.put("value", userinfoAgeCount);

        maps.add(map);
        maps.add(map2);
        maps.add(map3);
        maps.add(map4);
        maps.add(map5);
        maps.add(map6);
        return maps;
    }

    public Map<String, Object> getPinRate(SysUser user) throws Exception {
        Map<String, Object> map = new HashMap<>(10);
        //当前管理员组织架构
        HashSet<Long> orgIds = getSysUserOrgId(user);

        Map<String, Object> params = new HashMap<>();
        //params.put("orgIds", orgIds);

        //每月核销总数
        ArrayList<Integer> hairs = new ArrayList<>();
        //每月发放总数
        ArrayList<Integer> grants = new ArrayList<>();
        //每月核销率
        ArrayList<Integer> lv = new ArrayList<>();
        //近六个月月份
        List<String> months = getLastMonths(6);

        int pinRate6 = couponsRecordMapper.getPinRate6(params);
        int grant6 = couponsRecordMapper.getGrant6(params);

        int pinRate5 = couponsRecordMapper.getPinRate5(params);
        int grant5 = couponsRecordMapper.getGrant5(params);

        int pinRate4 = couponsRecordMapper.getPinRate4(params);
        int grant4 = couponsRecordMapper.getGrant4(params);
        //上上月
        int pinRate3 = couponsRecordMapper.getPinRate3(params);
        int grant3 = couponsRecordMapper.getGrant3(params);
        //上月
        int pinRate2 = couponsRecordMapper.getPinRate2(params);
        int grant2 = couponsRecordMapper.getGrant2(params);
        //当前月
        int pinRate = couponsRecordMapper.getPinRate(params);
        int grant = couponsRecordMapper.getGrant(params);

        //添加近六月核销总数
        hairs.add(pinRate6);
        hairs.add(pinRate5);
        hairs.add(pinRate4);
        hairs.add(pinRate3);
        hairs.add(pinRate2);
        hairs.add(pinRate);

        //获取发放总数
        int count = couponsRecordMapper.getCountGrant(params);
        //获取所有月份总核销数
        int pinCount = couponsRecordMapper.getCountPins(params);
        //第一个月得发放总数
        int one = count - (grant + grant2 + grant3 + grant4 + grant5) - (pinCount - pinRate - pinRate2 - pinRate3 - pinRate4 - pinRate5);
        grants.add(grant6);
        //第二个月得发放总数
        int two = count - (grant + grant2 + grant3 + grant4) - (pinCount - pinRate - pinRate2 - pinRate3 - pinRate4);
        grants.add(grant5);
        //第三个月得发放总数
        int three = count - (grant + grant2 + grant3) - (pinCount - pinRate - pinRate2 - pinRate3);
        grants.add(grant4);
        //第四个月得发放总数
        int four = count - (grant + grant2) - (pinCount - pinRate - pinRate2);
        grants.add(grant3);
        //第五个月得发放总数
        int five = count - (grant) - (pinCount - pinRate);
        grants.add(grant2);
        //第六个月得发放总数
        grants.add(grant);

        //计算核销率 核销率 = 当前月核销总数/发放总数  发放总数 = 之前累计剩余发放数总和
        int heXiao = getHeXiao(pinRate6, one);
        getHeXiao(pinRate5, two);
        getHeXiao(pinRate4, three);
        getHeXiao(pinRate3, four);
        getHeXiao(pinRate2, five);
        getHeXiao(pinRate, count);

        //添加核销率
        lv.add(heXiao);
        lv.add(getHeXiao(pinRate5, two));
        lv.add(getHeXiao(pinRate4, three));
        lv.add(getHeXiao(pinRate3, four));
        lv.add(getHeXiao(pinRate2, five));
        lv.add(getHeXiao(pinRate, count));

        if (Collections.max(hairs) <= 0 && Collections.max(grants) <= 0) {
            map.put("code", "9999");
            return map;
        }

        //x轴月份
        map.put("months", months);
        //核销总数
        map.put("pin", hairs);
        //发放总数
        map.put("grant", grants);
        //核销率
        map.put("pinLv", lv);

        Integer max = Collections.max(Arrays.asList(Collections.max(hairs), Collections.max(grants)));
        //计算步长
        Integer interval = 0;
        if (max < 100) {
            interval = max / 3;
        } else {
            if ((max / 100 % 2 == 0)) {
                max = ((max / 100) + 2) * 100;
            } else {
                max = ((max / 100) + 1) * 100;
            }
            interval = max / 5;
        }

        map.put("yData", max);
        map.put("interval", interval);
        map.put("code", "200");
        return map;
    }


    /**
     * 获取近x个月月份 包含当前月
     *
     * @param size
     * @return
     */
    public static List<String> getLastMonths(int size) {
        SimpleDateFormat sdf = new SimpleDateFormat("M月");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        List<String> list = new ArrayList(size);
        for (int i = 0; i < size; i++) {
            c.setTime(new Date());
            c.add(Calendar.MONTH, -i);
            Date m = c.getTime();
            list.add(sdf.format(m));
        }
        Collections.reverse(list);
        return list;
    }

    /**
     * 计算核销率
     */
    public Integer getHeXiao(double pin, double grant) {
        if (grant <= 0) {
            return 0;
        }
        return (int) (pin / grant) * 100;
    }

    /**
     * 获取本月、本年理发店或缝纫店核销
     */
    public Map<String, Object> getPinByType(String type, String flag, SysUser user, String all) throws Exception {
        //获取当前管理员组织架构
        HashSet<Long> sysUserOrgId = getSysUserOrgId(user);

        HashMap<String, Object> map = new HashMap<>();
        //数据
        ArrayList<Integer> datas = new ArrayList<>();
        //y轴name
        ArrayList<String> names = new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("flag", flag);
        //params.put("orgIds", sysUserOrgId);
        List<DataVo> lists = couponsRecordMapper.getPinByType(params);
        //截取lists
        if (Util.isNull(all) && lists.size() > 6) {
            List<DataVo> dataVos = lists.subList(0, 6);
            dataVos.sort((x, y) -> Integer.compare(x.getCountNum(), y.getCountNum()));
            for (DataVo dataVo : dataVos) {
                names.add(dataVo.getName());
                datas.add(dataVo.getCountNum());
            }
        } else {
            lists.sort((x, y) -> Integer.compare(x.getCountNum(), y.getCountNum()));
            for (DataVo dataVo : lists) {
                names.add(dataVo.getName());
                datas.add(dataVo.getCountNum());
            }
        }

        map.put("names", names);
        map.put("data", datas);
        Optional<DataVo> max = lists.stream().max(Comparator.comparingInt(DataVo::getCountNum));
        //System.out.println("max.get() = " + max.get());
        map.put("max", max.get().getCountNum() + 100);
        return map;
    }

    public Map<String, Object> getLast12Months(SysUser user) throws Exception {
        //获取当前管理员组织架构
        HashSet<Long> sysUserOrgId = getSysUserOrgId(user);
        Map<String, Object> map = new HashMap<>();
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", 1);
        //params.put("orgIds", sysUserOrgId);
        //理发核销数
        List<Integer> last12Months = couponsRecordMapper.getLast12Months(params);
        //缝纫核销数
        params.put("type", 2);
        List<Integer> last12Months2 = couponsRecordMapper.getLast12Months(params);
        //近12月月份
        List<String> lastMonths = getLastMonths(12);
        map.put("months", lastMonths);
        map.put("lifaPins", last12Months);
        map.put("fengrenPins", last12Months2);

        //计算y轴坐标
        Integer max = Collections.max(Arrays.asList(Collections.max(last12Months), Collections.max(last12Months)));
        //计算y轴坐标


        //计算步长
        Integer interval = 0;
        if (max < 100) {
            interval = max / 3;
        } else {
            if ((max / 100 % 2 == 0)) {
                max = ((max / 100) + 2) * 100;
            } else {
                max = ((max / 100) + 1) * 100;
            }
            interval = max / 5;
        }
        map.put("yData", max);
        map.put("interval", interval);

        return map;

    }
}
